﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Reflection
{
    public static class MemberInfoExtension
    {
        public static object GetAttributeOfType(this MemberInfo member, Type attribute, bool inherit)
        {
            if (member != null)
                return member.GetCustomAttributes(attribute, inherit).FirstOrDefault();
            else
                return null;
        }
        public static Tatt GetAttribute<Tatt>(this MemberInfo member, bool inherit)
            where Tatt : Attribute
        {
            if (member != null)
                return (Tatt)member.GetCustomAttributes(typeof(Tatt), inherit).FirstOrDefault();
            else
                return null;
        }
        public static Tatt GetAttribute<Tatt>(this MemberInfo member)
            where Tatt : Attribute
        {
            return (Tatt)member.GetAttribute<Tatt>(true);
        }

        public static IEnumerable<Tatt> GetAttributes<Tatt>(this MemberInfo member, bool inherit)
            where Tatt : Attribute
        {
            if (member != null)            
                foreach (var item in member.GetCustomAttributes(typeof(Tatt), inherit)
                    .Cast<Tatt>())                
                    yield return item;
        }

        public static bool IsAttribute<Tatt>(this MemberInfo member)
            where Tatt : Attribute
        {
            return (Tatt)member.GetAttribute<Tatt>(true) != null;
        }
        public static object GetAttributeOfType(this MemberInfo member, Type attribute)
        {
            return GetAttributeOfType(member, attribute, true);
        }

        public static IEnumerable<object> GetAttributesOfType(this MemberInfo member, Type attribute, bool inherit)
        {
            if (member != null)
                return member.GetCustomAttributes(attribute, inherit);
            else
                return null;
        }
    }
}
